import tkinter as tk
from docx import Document
import windnd


class AppUi(tk.Tk):
    def __init__(self):
        super().__init__()
        self.wm_attributes('-topmost', 1)

        sw = self.winfo_screenwidth()
        sh = self.winfo_screenheight()

        ww = 1500
        wh = 150
        self.geometry(
            "%dx%d+%d+%d" %
            (ww, wh, (sw - ww) / 2, (sh - wh) / 2))
        self.after(1, lambda: self.focus_force())

        self.title('表格填写助手  -v1.0 by cbl')

        first_row = tk.Frame()
        first_row.pack()
        tk.Label(first_row, text='行号').pack(side=tk.LEFT)
        self.table_row_num = tk.StringVar()
        self.table_row_num.set('2')
        self.table_row_num_entry = tk.Entry(
            first_row, textvariable=self.table_row_num)
        self.table_row_num_entry.pack(side=tk.LEFT)

        tk.Label(first_row, text='文件路径').pack(side=tk.LEFT)
        self.file_path = tk.StringVar()
        self.file_path_entry = tk.Entry(
            first_row, textvariable=self.file_path)
        self.file_path_entry.pack(side=tk.LEFT)
        windnd.hook_dropfiles(self.file_path_entry.winfo_id(), self.fuc)
        self.read_table_btn = tk.Button(
            first_row, text='读取', command=self.read_table)
        self.read_table_btn.pack(side=tk.LEFT)
        self.table_frame = tk.Frame()
    def read_table(self):
        row_num = int(self.table_row_num.get())
        file_path = self.file_path.get()
        docx_read = Document(file_path)
        table_read = docx_read.tables[0]
        first_row_read = table_read.rows[1].cells
        first_row_info = {}
        for idx, cell in enumerate(first_row_read):
            first_row_info[f'{str(idx)} {cell.text}'] = idx
        self.table_frame.destroy()
        self.table_frame = tk.Frame()
        self.table_frame.pack()
        for k, v in first_row_info.items():
            tk.Label(self.table_frame, text=k).pack(side=tk.LEFT)



    def fuc(self, l):
        self.file_path_entry.delete(0, 'end')
        for i in l:
            self.file_path_entry.insert("end", i.decode("gbk"))


if __name__ == "__main__":
    app = AppUi()
    app.mainloop()
